<?php
// +-------------+------------------+------+-----+---------+----------------+
// | Field       | Type             | Null | Key | Default | Extra          |
// +-------------+------------------+------+-----+---------+----------------+
// | id          | int(11)          | NO   | PRI | NULL    | auto_increment |
// | uid         | int(11) unsigned | YES  | MUL | 0       |                |
// | group_id    | int(11) unsigned | YES  | MUL | 0       |                |
// | member_id   | int(11) unsigned | YES  |     | 0       |                |
// | create_time | int(11) unsigned | YES  |     | 0       |                |
// | update_time | int(11) unsigned | YES  |     | 0       |                |
// +-------------+------------------+------+-----+---------+----------------+
namespace app\admin\model;

use app\admin\model\Base;
use app\admin\validate\AuthGroupAccess as Validate;
class AuthGroupAccess extends Base
{
    /**
     * 添加或更新用户所在组
     * @Author   Laifuzi
     * @DateTime 2018-06-07
     * @param    integer    $member_id 管理员ID
     * @param    integer    $group_id  AuthGroup ID
     * @return   array
     */
    public function createOrUpdateUserAccess($member_id, $group_id)
    {
        $res = ['status' => false, 'data' => [], 'msg' => "更新用户角色组失败"];

        $data = [
            'uid' => $member_id,
            'group_id' => $group_id,
        ];

        $validate = new Validate;
        if(!$validate->check($data)){
            $res['msg'] = $validate->getError();
            return $res;
        }

        $item = $this->where('uid', $member_id)->find();
        if(empty($item)){
            $is_update = false;
            $msg = '添加用户角色组设置成功';
        }else{
            $is_update = true;
            $data['id'] = $item['id'];
            $msg = '更新用户角色组设置成功';
        }
        $this->data($data)->isUpdate($is_update)->allowField(true)->save();

        $res = [
            'status' => true,
            'msg' => $msg,
            'data' => ['id' => $this->id],
        ];
        return $res;
    }
}
